package gold.digger;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC688 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public Map<String, Double> memo = new HashMap<>();

        public double knightProbability(int N, int K, int r, int c) {
            return dfs(N, K, r, c);
        }

        public double dfs(int N, int K, int r, int c) {
            if (r < 0 || r >= N || c < 0 || c >= N) return 0;
            if (K <= 0) return 1;
            if (N <= 1) return 0;

            String key = N + "_" + K + "_" + r + "_" + c;
            if (memo.containsKey(key)) return memo.get(key);
            double up1 = dfs(N, K - 1, r - 1, c - 2);
            double up2 = dfs(N, K - 1, r - 2, c - 1);
            double up3 = dfs(N, K - 1, r - 2, c + 1);
            double up4 = dfs(N, K - 1, r - 1, c + 2);

            double down1 = dfs(N, K - 1, r + 1, c - 2);
            double down2 = dfs(N, K - 1, r + 2, c - 1);
            double down3 = dfs(N, K - 1, r + 2, c + 1);
            double down4 = dfs(N, K - 1, r + 1, c + 2);

            double total = (up1 + up2 + up3 + up4 + down1 + down2 + down3 + down4) / 8;
            memo.put(key, total);
            return total;
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.knightProbability(3, 2, 0, 0));
        System.out.println(solution.knightProbability(1, 0, 0, 0));
    }

    public static void main(String[] args) throws Exception {
        LC688 an = new LC688();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
